import React from 'react';
import { 
  Upload, 
  Button, 
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Modal,
  List,
  Card
} from 'antd';
import { 
  LoadingOutlined,
  InboxOutlined,
  DeleteOutlined,
  FilePdfOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './ImageToPDF.module.css';

const { Dragger } = Upload;
const { Text } = Typography;

const ImageToPDF: React.FC = () => {
  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([]);
  const [converting, setConverting] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [convertedFile, setConvertedFile] = React.useState<{
    blob: Blob;
    fileName: string;
  } | null>(null);

  const handleFileSelect = (info: any) => {
    const file = info.file;
    if (!file) return;

    setError('');
    setProgress(0);

    if (!pdfService.validateImageFile(file)) {
      setError('请上传有效的图片文件（JPG/PNG，小于10MB）');
      return;
    }

    setSelectedFiles(prev => [...prev, file]);
  };

  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleConvert = async () => {
    if (selectedFiles.length === 0) {
      message.warning('请先选择图片文件');
      return;
    }

    try {
      setConverting(true);
      setError('');
      setProgress(0);
      setConvertedFile(null);
      
      const response = await pdfService.imagesToPDF(selectedFiles);
      
      if (response.code === 200 && response.data?.blob && response.data?.fileName) {
        setProgress(100);
        setConvertedFile({
          blob: response.data.blob,
          fileName: response.data.fileName
        });
        
        message.success('转换成功！');

        Modal.confirm({
          title: '文件已准备好',
          content: '是否立即下载转换后的PDF文件？',
          okText: '立即下载',
          cancelText: '稍后下载',
          onOk() {
            const hide = message.loading('正在下载...', 0);
            
            try {
              pdfService.downloadFile(response.data!.blob!, response.data!.fileName!);
              hide();
              message.success('文件下载成功');
            } catch (error) {
              hide();
              message.error('文件下载失败，请重试');
            }
          },
          onCancel() {
            message.info('您可以稍后点击"重新下载"按钮下载文件');
          }
        });
      } else {
        setError('转换失败，请重试');
        message.error('转换失败，请重试');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '转换过程出错';
      setError(errorMessage);
      message.error('转换失败：' + errorMessage);
    } finally {
      setConverting(false);
    }
  };

  const handleDownload = () => {
    if (!convertedFile) return;

    const hide = message.loading('正在下载...', 0);
    
    try {
      pdfService.downloadFile(convertedFile.blob, convertedFile.fileName);
      hide();
      message.success('文件下载成功');
    } catch (error) {
      hide();
      message.error('文件下载失败，请重试');
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.jpg,.jpeg,.png',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <div className={styles.uploadSection}>
        <Dragger {...uploadProps} className={styles.draggerContainer}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined style={{ 
              fontSize: '48px', 
              color: '#1890ff',
              marginBottom: '8px'
            }} />
          </p>
          <p className="ant-upload-text" style={{ padding: '0 20px' }}>
            点击或拖拽图片文件到此区域
          </p>
          <p className="ant-upload-hint" style={{ padding: '0 20px' }}>
            支持JPG、PNG格式，单个文件不超过10MB
          </p>
        </Dragger>

        {selectedFiles.length > 0 && (
          <List
            className={styles.fileList}
            itemLayout="horizontal"
            dataSource={selectedFiles}
            renderItem={(file, index) => (
              <List.Item
                actions={[
                  <Button 
                    type="text" 
                    danger 
                    icon={<DeleteOutlined />}
                    onClick={() => handleRemoveFile(index)}
                  />
                ]}
              >
                <List.Item.Meta
                  title={file.name}
                  description={`${(file.size / (1024 * 1024)).toFixed(2)}MB`}
                />
              </List.Item>
            )}
          />
        )}
        
        <div className={styles.controlSection}>
          <Button
            type="primary"
            icon={converting ? <LoadingOutlined /> : <FilePdfOutlined />}
            onClick={handleConvert}
            loading={converting}
            disabled={selectedFiles.length === 0 || !!error}
          >
            {converting ? '转换中...' : '开始转换'}
          </Button>
        </div>
      </div>

      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          className={styles.alert}
        />
      )}

      {convertedFile && (
        <Alert
          className={styles.uploadSection}
          message={
            <Space size="middle" align="center" style={{ 
              width: '100%', 
              justifyContent: 'center',
              flexWrap: 'wrap',
              gap: '8px'
            }}>
              <Text type="success">
                文件已转换完成，可随时下载
              </Text>
              <Button 
                type="primary" 
                icon={<FilePdfOutlined />}
                onClick={handleDownload}
              >
                重新下载
              </Button>
            </Space>
          }
          type="success"
          showIcon
        />
      )}

      {converting && (
        <div className={styles.progressContainer}>
          <Progress 
            percent={progress} 
            status={progress === 100 ? "success" : "active"}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
        </div>
      )}
    </div>
  );
};

export default ImageToPDF; 